package com.wpw.java7demo.jvm;

import java.lang.ref.WeakReference;

public class WeakRef {

	public static class User {

		public User(int id, String name) {

			this.id = id;

			this.name = name;

		}

		public int id;

		public String name;

		@Override

		public String toString() {

			return "User [id=" + id + ", name=" + name + "]";

		}

	}

	public static void main(String[] args) {

		User u = new User(1, "hey");

		//构造弱引用

		WeakReference<User> userWeakRef = new WeakReference<User>(u);

		u = null;// 去除强引用

		System.out.println(userWeakRef.get());// 从弱引用中重新获取对象

		System.gc();// GC

		//不管当前内存空间足够与否，都会回收它的内存

		System.out.println("After GC:");

		System.out.println(userWeakRef.get());// 重新尝试从弱引用中获取对象

	}

}
